package wang.lxl.skipTable;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * 跳表
 */
public class SkipTable<E> {
    private static final int MAX_LEVEL = 1 << 6;// 最大层数
    // 跳表数据结构
    private SkipNode top;
    private int level = 0;
    // 用于产生随机数的random对象
    private Random random = new Random();
    private int valCount = 0;// 保存最低层的节点的个数(存储数据的有效节点的个数)

    public SkipTable() {
        this(4);// 创建默认高度的跳表
    }

    // 初始化跳表
    public SkipTable(int level) {
        this.level = level;
        int i = level;
        SkipNode temp = null;
        SkipNode prev = null;
        while (i-- != 0) {
            temp = new SkipNode(null, Double.MIN_VALUE);
            temp.down = prev;
            prev = temp;
        }
        top = temp;// 头节点
    }

    /**
     * 使用抛硬币产生节点的高度
     *
     * @return
     */
    private int getRandomLevel() {
        int lev = 1;
        while ((random.nextInt() & 0x1) == 0) {
            lev++;
        }
        return lev > MAX_LEVEL ? MAX_LEVEL : lev;
    }

    /**
     * 查询
     *
     * @param score
     * @param <T>
     * @return
     */
    public <T> T get(double score) {
        SkipNode<T> t = top;
        while (Objects.nonNull(t)) {
            if (t.score == score) {
                return t.val;
            }
            if (Objects.isNull(t.next)) {
                if (Objects.nonNull(t.down)) {
                    t = t.down;
                    continue;
                } else {
                    return null;
                }
            }
            if (t.next.score > score) {
                t = t.down;
            } else {
                t = t.next;
            }
        }
        return null;
    }

    /**
     * 添加节点
     *
     * @param score
     * @param val
     */
    public void put(double score, E val) {
        // 1,找到要插入的位置
        SkipNode<E> t = top, cur = null;// 若cur不为空,表示当前score值的节点存在
        List<SkipNode<E>> path = new ArrayList<>();// 记录每一层当前节点的前去节点
        while (Objects.nonNull(t)) {
            if (t.score == score) {
                cur = t;// 表示存在该值的点,需要更新该节点
                break;
            }
            if (Objects.isNull(t.next)) {
                path.add(t);//需要向下查找,先记录该节点
                if (Objects.nonNull(t.down)) {
                    t = t.down;
                    continue;
                } else {
                    break;
                }
            }
            if (t.next.score > score) {
                path.add(t);// 需要向下查找,先记录该节点
                if (Objects.isNull(t.down)) {
                    break;
                }
                t = t.down;
            } else {
                t = t.next;
            }
        }
        if (Objects.nonNull(cur)) {
            while (Objects.nonNull(cur)) {
                cur.val = val;
                cur = cur.down;
            }
        } else {
            // 当前表中不存在score值的节点,需要从下到上插入
            int lev = getRandomLevel();
            if (lev > level) {
                // 需要更新top这一列的节点数量,同时需要在path中增加这些新的首节点
                SkipNode<E> temp = null;
                SkipNode<E> prev = top;// 前驱节点现在是top了
                while (level++ != lev) {
                    temp = new SkipNode<>(null, Double.MIN_VALUE);
                    path.add(0, temp);// 添加到path的首部
                    temp.down = prev;
                    prev = temp;
                }
                top = temp;// 头节点
                level = lev;// level长度增加到新的长度
            }
            // 从后向前遍历path中的每一个节点,在其后面增加一个新的节点
            SkipNode<E> downTemp = null, temp = null, prev = null;
//            System.out.println("当前深度为: " + level + "当前path的长度为: " + path.size());
            for (int i = level - 1; i >= level - lev; i--) {
                temp = new SkipNode<>(val, score);
                prev = path.get(i);
                temp.next = prev.next;
                prev.next = temp;
                temp.down = downTemp;
                downTemp = temp;
            }

            this.valCount++;
        }
    }

    public void delete(double score) {
        SkipNode<E> t = top;
        while (Objects.nonNull(t)) {
            if (Objects.isNull(t.next)) {
                t = t.down;
                continue;
            }
            if (t.next.score == score) {
                // 找到了需要删除的节点
                t.next = t.next.next;
                t = t.down;
                // 删除当前节点后,还需要继续查找之后需要删除的节点
                continue;
            }
            if (t.next.score > score) {
                t = t.down;
            } else {
                t = t.next;
            }
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        SkipNode<E> t = top; //当前遍历到的节点
        SkipNode<E> topDown = top;// 最底层的第一个节点
        SkipNode<E> culLevelFirst = top;//当前遍历到的层的第一个节点
        SkipNode<E> next=null;// 最底层的下一个节点总是在变化
        while (Objects.nonNull(topDown.down)){
            topDown = topDown.down;
        }
        int count = this.valCount;
        for (int i = 1; i < this.level; i++) {
            next = topDown;
            t = culLevelFirst;
            for (int j = 0; j < count; j++) {
                if (Objects.nonNull(t) && t.score == next.score) {
                    sb.append(t.score+" ");
                    t = t.next;
                } else {
                    // 添加制表符
                    sb.append("\t"+" ");
                }
                next = next.next;
            }
            sb.append("\n");
            culLevelFirst = culLevelFirst.down;
        }
        while (Objects.nonNull(topDown)) {
            sb.append(topDown.score+" ");
            topDown = topDown.next;
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        SkipTable<String> list = new SkipTable<>();
        list.put(1.0, "1.0");
        System.out.println("-------------------------------");
        list.put(2.0, "2.0");
        System.out.println(list);
        System.out.println("-------------------------------");
        list.put(3.0, "3.0");
        System.out.println(list);
        System.out.println("-------------------------------");
        list.put(4.0, "4.0");
        System.out.println(list);
        System.out.println("-------------------------------");
//        list.put(4.0, "5.0");
        list.put(5.0, "5.0");
        list.put(6.0, "6.0");
        list.put(7.0, "7.0");
        System.out.println(list);
        System.out.println("-------------------------------");
//        list.delete(3.0);
//        list.delete(3.5);
//        System.out.println(list);
//        System.out.println("查找4.0" + list.get(4.0));

    }

    /**
     * 跳表节点
     *
     * @param <E>
     */
    private static class SkipNode<E> {
        E val;// 存储的数据
        double score;// 按照这个分数值进行从小到大排序
        SkipNode<E> next, down;// next指针,指向下一层的指针

        public SkipNode(E val, double score) {
            this.val = val;
            this.score = score;
        }

        public SkipNode() {
        }
    }

}
